/*
 * @Author: lizhil
 * @Date: 2021-09-19 23:49:13
 * @Last Modified by: lizhil
 * @Last Modified time: 2024-05-29 14:59:20
 */
import _ from 'lodash-es'

export default {
  inject: ['appPageList'],
  emits: ['change', 'update:modelValue', 'update:detail'],
  props: {
    beforeSubmit: null,
    beforeFetch: null,

    // v-model 是否显示弹框
    modelValue: {
      type: Boolean,
      default: false,
    },

    params: null, // 固定参数

    detail: null, // 表单内容

    json: null, // JSON表单

    defaultDetail: null, // 默认详情内容
  },
  data() {
    return {
      appShowDetail: false,
      appDetail: null, // 详情内容
      appModel: this.$route.meta.appModel,
      appApi: null,
      appSaving: false,
    }
  },
  computed: {
    appId() {
      return this.$route.meta.appId || 'id'
    },
  },
  created() {
    if (!this.appApi) this.appApi = this.appModel
  },
  watch: {
    modelValue() {
      if (this.modelValue) {
        this.appGetDetail()
      }

      this.appShowDetail = this.modelValue
    },
    appDetail() {
      this.$emit('update:detail', this.appDetail)
      // this.$emit('update:modelDetail', this.appDetail)
    },
  },
  methods: {
    /**
     * 获取prop或者appPageList传递的参数
     * @param {*} key
     * @returns
     */
    getProps(key) {
      const appKey = 'app' + key.charAt(0).toUpperCase() + key.slice(1)

      // props
      if (this[key]) {
        return this[key]
      }
      // 组件自身
      else if (this[appKey]) {
        return this[appKey]
      }
      // 注入appPageList
      else if (this.appPageList && this.appPageList[appKey]) {
        return this.appPageList[appKey]
      }
    },

    /**
     * 获取详情
     */
    appGetDetail() {
      const id = this.detail[this.appId]
      const defaultDetail = this.getProps('defaultDetail')
      const beforeFetch = this.getProps('beforeFetch')
      const afterFetch = this.getProps('afterFetch')

      const setDetail = (detail = {}) => {
        // 处理默认值
        if (defaultDetail) {
          for (const key in defaultDetail) {
            if (detail[key] === null || detail[key] === undefined) {
              detail[key] = defaultDetail[key]
            }
          }
        }

        // 取回数据前
        if (beforeFetch) beforeFetch(detail)

        this.appDetail = detail

        // 取回数据后
        if (afterFetch) afterFetch()
      }

      setDetail(this.detail)

      // 详情
      if (id) this.$http(`${this.appApi}/${id}`).then(res => setDetail(res))
    },

    /**
     * 处理提交（保存）
     */
    appHandleSubmit(e, goBack) {
      if (e) e.preventDefault()
      if (this.appSaving) return

      let appDetail = {
        ...this.appDetail,
        ...this.params,
      }

      this.$refs.appForm.validate(valid => {
        if (valid) {
          this.appSaving = true

          const beforeSubmit = this.getProps('beforeSubmit')
          const afterSubmit = this.getProps('afterSubmit')

          if (beforeSubmit) {
            const reulst = beforeSubmit(appDetail)
            if (reulst == false) return
          }

          const id = appDetail[this.appId]

          if (id) {
            this.$http
              .put(`${this.appApi}/${id}`, appDetail)
              .then(() => {
                this.$message.success('保存成功')
                if (afterSubmit) afterSubmit()
                this.$emit('change')
                this.appHandleClose()
              })
              .finally(() => (this.appSaving = false))
          } else {
            this.$http
              .post(`${this.appApi}`, appDetail)
              .then(() => {
                this.$message.success('添加成功')
                if (afterSubmit) afterSubmit()
                this.$emit('change')
                this.appHandleClose()
              })
              .finally(() => (this.appSaving = false))
          }
        } else {
          return false
        }
      })
    },
    /**
     * 关闭弹窗
     */
    appHandleClose() {
      // 清除下一次打开弹框后再次出现的提示语
      // this.$nextTick(function () {
      //   this.$refs.appForm.elForm.clearValidate()
      // })

      this.appShowDetail = false
      this.$emit('update:modelValue', false)
    },
  },
}
